package com.example.controller;


import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.annotation.Log;
import com.example.common.result.PageResult;
import com.example.common.result.Result;
import com.example.entity.dto.PurchaseOrder.PurmcListDto;
import com.example.entity.dto.PurtbDto;
import com.example.entity.dto.RequisitionPurchaseDto;
import com.example.entity.hz.HttpResult;
import com.example.entity.hz.ShenHe;
import com.example.entity.vo.PurchaseOrder.ProductPriceVo;
import com.example.entity.vo.PurchaseOrder.PurmbVo;
import com.example.entity.vo.PurchaseOrder.PurmcListVo;
import com.example.entity.vo.RequisitionPurchaseVo;
import com.example.entity.vo.pc.DDPHZBfinalListVo;
import com.example.entity.vo.pc.DDPHZBlistVo;
import com.example.entity.yifei.Cmsmv;
import com.example.entity.yifei.Purma;
import com.example.entity.yifei.Purta;
import com.example.entity.yifei.Purtb;
import com.example.entity.ymlConfig.YmlConfig;
import com.example.mapper.*;
import com.example.service.PurtbService;
import com.example.service.impl.ActFlowCommService;
import com.example.untils.HttpClientUtil;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-02-19
 */
@RestController
@RequestMapping("/api/purtb")
@Api(tags = "请购单相关接口")
@Slf4j
public class PurtbController {
    @Resource
    private PurtcMapper purtcMapper;
    @Resource
    private PurtbService purtbService;
    @Resource
    private  PurtaMapper purtaMapper;
    @Resource
    private PurtbMapper purtbMapper;
    @Resource
    private CmsmqMapper cmsmqMapper;
    @Resource
    private PurmbMapper purmbMapper;

    @Resource
    private PurmaMapper purmaMapper;
    @Resource
    private PurtdMapper purtdMapper;

    @Resource
    private PurtmMapper purtmMapper;
    @Autowired
    private ActFlowCommService actFlowCommService;

    @Resource
    private CmsmvMapper cmsmvMapper;

    /*@PostMapping("/synchronous")
    @ApiOperation("请购单身同步信息")
    public Result synchronous(){
        purtbService.synchronous();
        return Result.success();
    }*/
    @GetMapping("/selectPurtaList")
    @ApiOperation("查询请购单头信息")
    public Result selectPurtaList(){
        List<Purta> purtas = purtbMapper.selectPurtaList();
        return Result.success(purtas);
    }

    @PostMapping("/selectPurtbListByTb001WithTb002")
    @ApiOperation("查询请购单头信息")
    public Result selectPurtbList(@RequestBody List<PurtbDto> purtbDtos){
        List<RequisitionPurchaseVo> purtbs = purtbMapper.selectPurtbListByTb001WithTb002(purtbDtos);
        return Result.success(purtbs);
    }

    @PostMapping("/selectAll")
    @ApiOperation("请购单单身维护信息")
    public Result<PageResult> selectAll(@RequestParam(defaultValue = "1") Integer current,
                                        @RequestParam(defaultValue = "10") Integer size,
                                        @RequestBody RequisitionPurchaseDto requisitionPurchaseDto){
        if(StringUtils.isNotEmpty(requisitionPurchaseDto.getProductName())) {
            requisitionPurchaseDto.setProductName
                    (requisitionPurchaseDto.getProductName().replaceAll("([\\[\\]*+_%^])", "/$1"));
        }
//        PageResult page = ;
        return purtbService.selectPage(current,size,requisitionPurchaseDto);
    }

    @PostMapping("/refPriceByCustomId")
    @ApiOperation("供应商带出参考价格")
    public Result<List<ProductPriceVo>> refPriceByCustomId(@RequestBody List<ProductPriceVo> dto) {
//        for (ProductPriceVo purchaseVo : dto) {
//            if ("90000001".equals(purchaseVo.getProductId().trim())) {
//                RequisitionPurchaseVo temp = purtdMapper.select90000001(purchaseVo.getProductName(), purchaseVo.getSpecifications());
//                if (temp != null) {
//                    purchaseVo.setSupplierNo(temp.getSupplierNo());
//                    purchaseVo.setSupplierName(temp.getSupplierName());
//                    purchaseVo.setCurrency(temp.getCurrency());
//                    purchaseVo.setTaxRate(temp.getTaxRate());
//                    purchaseVo.setPayment(temp.getPayment());
//                    purchaseVo.setPaymentId(temp.getPaymentId());
//                    purchaseVo.setReferencePrice(temp.getReferencePrice());
//                } else {
//                    purchaseVo.setSupplierNo(null);
//                    purchaseVo.setSupplierName(null);
//                    purchaseVo.setCurrency(null);
//                    purchaseVo.setTaxRate(null);
//                    purchaseVo.setPayment(null);
//                    purchaseVo.setPaymentId(null);
//                    purchaseVo.setReferencePrice(null);
//                }
//            }
//        }
        for (ProductPriceVo purchaseVo :dto) {
            List<PurmbVo> list;
            if ("90000001".equals(purchaseVo.getProductId().trim())) {
                list = purmbMapper.purmbOne
                        (new PurmcListDto(purchaseVo.getProductId(), purchaseVo.getProductName(), purchaseVo.getSpecifications(), purchaseVo.getUnit(),
                                purchaseVo.getCurrency(), purchaseVo.getSupplierNo(), "", ""));
            }else {
                list = purmbMapper.purmbOne
                        (new PurmcListDto(purchaseVo.getProductId(), "", "", purchaseVo.getUnit(),
                                purchaseVo.getCurrency(), purchaseVo.getSupplierNo(), "", ""));
            }
            purchaseVoList(purchaseVo, list);
        }
        return Result.success(dto);
    }

    private void purchaseVoList(ProductPriceVo purchaseVo, List<PurmbVo> list) {
        for (PurmbVo item : list) {
            if ("Y".equals(item.getNumberPrice().trim())) {
                item.setNum(purchaseVo.getNum());
                List<PurmcListVo> purmcListVos = purmbMapper.purmcList(new PurmcListDto(item.getProductId(),"","",item.getUnit(),
                        item.getCurrency(), item.getSupplier(),"",purchaseVo.getNum()));
                if (!purmcListVos.isEmpty()){
                    for (PurmcListVo g : purmcListVos) {
                        if (Double.parseDouble(purchaseVo.getNum()) > g.getNumber()){
                            purchaseVo.setReferencePrice(g.getPrice());
                            // 供应商信息
                            GysXxVo(purchaseVo, item);
                            break;
                        }else {
                            purchaseVo.setReferencePrice(item.getUnitPrice());
                            // 供应商信息
                            GysXxVo(purchaseVo, item);
                        }
                    }
                }else {
                    purchaseVo.setReferencePrice(item.getUnitPrice());
                    // 供应商信息
                    GysXxVo(purchaseVo, item);
                }
            } else {
                purchaseVo.setReferencePrice(item.getUnitPrice());  // 单价
                // 供应商信息
                GysXxVo(purchaseVo, item);
            }
        }
    }

    private void GysXxVo(ProductPriceVo purchaseVo, PurmbVo item) {
        Purma purma = purmaMapper.selectOne(new LambdaQueryWrapper<Purma>()
                .eq(Purma::getMa001, purchaseVo.getSupplierNo()));
        if(purma!=null){
            Cmsmv cmsmv = cmsmvMapper.selectOne(new LambdaQueryWrapper<Cmsmv>().eq(Cmsmv::getMv001, purma.getMa047()));
            if (cmsmv!=null){
                purchaseVo.setPurchaserNo(cmsmv.getMv001());
                purchaseVo.setPurchaserName(cmsmv.getMv002());
                purchaseVo.setPurchasing(cmsmv.getMv002());
            }
            purchaseVo.setSupplierNo(purma.getMa001());
            purchaseVo.setSupplierName(purma.getMa002());
            purchaseVo.setCurrency(item.getCurrency());
            purchaseVo.setTaxRate(purma.getMa064());
            purchaseVo.setPayment(purma.getMa025());
            purchaseVo.setPaymentId(purma.getMa055());
            purchaseVo.setUnit(item.getUnit());
            purchaseVo.setTaxCategory(purma.getMa044());
        }
        return;
    }

    @Log("上报请购单")
    @ApiOperation("上报请购单")
    @GetMapping ("/report")
    @DSTransactional
    public Result report(
            @RequestParam String TC001, @RequestParam String TC002, @RequestParam String username,@RequestParam String leader
    ) {
        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        if (StringUtils.isEmpty(username)) {
            return Result.error("用户名为空");
        }
        String formkey = "purtb";
        String beanName = formkey + "ServiceImpl";
        if (TC001.equals("AAPZ")) {
            formkey = "shuwuqinggou";
        } else {
            formkey = "yibanqinggou";
        }
        ProcessInstance processInstance;
        //关联业务 bussinessKey
        String bussinessKey = formkey + ":" + TC001 + ":" + TC002;
        String id = TC001 + ":" + TC002;
        Boolean b = actFlowCommService.isOnly(bussinessKey, formkey);
        Boolean b2 = purtbService.tc30IsN(TC001, TC002);
        if (b && b2) {
            processInstance = actFlowCommService.startProcess(formkey, beanName, bussinessKey, id, username, leader);
        } else {
            return Result.error("有相同单据正在审核或该单据已审核完成");
        }
        //获取流程实例id
        String processInstanceId = processInstance.getId();
        List<Task> taskList = actFlowCommService.myTaskList(username);
        if (!CollectionUtils.isEmpty(taskList)) {
            for (Task task : taskList) {
                if (task.getAssignee().equals(username) &&
                        task.getProcessInstanceId().equals(processInstanceId)) {
                    log.info("ProcessInstanceId is {}", task.getProcessInstanceId());
                    log.info("taskid is {}",task.getId());
                    actFlowCommService.completeProcess("同意", username, task.getId(),"");
                }
            }
        }
        else {
            return Result.error("空任务！");
        }
        return Result.success("上报请购单成功");
    }
    @Log("撤审请购单")
    @ApiOperation("撤审请购单")
    @PostMapping("/withdraw")
    public Result withdraw(@RequestParam(defaultValue = "") String TC001,
                                @RequestParam(defaultValue = "") String TC002) {
        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        Purta purta = purtaMapper.selectOne(new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, TC001).eq(Purta::getTa002, TC002));
        if (purta == null) {
            return Result.error("请购单不存在");
        }
        ShenHe shenHe = new ShenHe();
        shenHe.setCom(YmlConfig.getYFCOMPANY());
        shenHe.setUser("DS");
        shenHe.setRq(TimeUtils.HZStdTime());
        shenHe.setType("UNDO");
        shenHe.setDb(TC001);
        shenHe.setDh(TC002);
        shenHe.setProgram("PURI05");

        HttpResult httpResult = HttpClientUtil.postHZ(shenHe);
        if (httpResult.getStatus().equals("成功")) {
            Purta purta1 = new Purta();
            purta1.setTa016("0");
            purtaMapper.update(purta1, new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, TC001).eq(Purta::getTa002, TC002));
            return Result.success("撤审成功");
        }
        return Result.success("撤审失败");
    }
    @Log("作废请购单")
    @ApiOperation("作废请购单")
    @PostMapping("/invalidate")
    public Result invalidate(@RequestParam(defaultValue = "") String TC001,
                           @RequestParam(defaultValue = "") String TC002) {
        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        Purta purta = purtaMapper.selectOne(new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, TC001).eq(Purta::getTa002, TC002));
        if (purta == null) {
            return Result.error("请购单不存在");
        }
        ShenHe shenHe = new ShenHe();
        shenHe.setCom(YmlConfig.getYFCOMPANY());
        shenHe.setUser("DS");
        shenHe.setRq(TimeUtils.HZStdTime());
        shenHe.setType("UNDO");
        shenHe.setDb(TC001);
        shenHe.setDh(TC002);
        shenHe.setProgram("PURI05");

        HttpResult httpResult = HttpClientUtil.postHZ(shenHe);
        if (httpResult.getStatus().equals("成功")) {
            Purta purta1 = new Purta();
            purta1.setTa016("0");
            purta1.setTa007("V");
            purtaMapper.update(purta1, new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, TC001).eq(Purta::getTa002, TC002));
            Purtb purtb=new Purtb();
            purtb.setTb025("V");
            purtbMapper.update(purtb,new LambdaQueryWrapper<Purtb>().eq(Purtb::getTb001,TC001).eq(Purtb::getTb002,TC002));
            return Result.success("作废成功");
        }
        return Result.success("作废失败");
    }

    @Log("请购单详情")
    @ApiOperation("请购单详情")
    @PostMapping("/queryXq")
    public Result<Map<String,Object>> queryXq(@RequestParam(defaultValue = "") String TC001,
                            @RequestParam(defaultValue = "") String TC002){

        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        Purta purta = purtaMapper.selectOne(new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, TC001).eq(Purta::getTa002, TC002));
        if (purta == null) {
            return Result.error("请购单不存在");
        }
        List<Purtb> purtbs = this.purtbMapper.selectList(new LambdaQueryWrapper<Purtb>().eq(Purtb::getTb001, TC001).eq(Purtb::getTb002, TC002));
        Map<String,Object> map = new HashMap<>();
        map.put("purta",purta);
        map.put("purtbList",purtbs);
        return Result.success(map);
    }

    @ApiOperation("请购单通过品号进行查询物料存库")
    @GetMapping("/queryPhKc/{ph}")
    public Result<DDPHZBfinalListVo> list(@PathVariable String ph) {
        DDPHZBfinalListVo res = new DDPHZBfinalListVo();
        List<DDPHZBlistVo> list = purtbMapper.queryPhKc(ph);
        res.setList(list);
        double expectNumsSum = 0;
        double orderNumsSum = 0;
        double stockNumsSum = 0;
        double expectOutputSum = 0;
        double expectPurchaseSum = 0;
        double expectReceivingSum = 0;
        double expectPickingSum = 0;
        for (DDPHZBlistVo item : list) {
            expectNumsSum += item.getExpectNums();
            orderNumsSum += item.getOrderNums();
            stockNumsSum += item.getStockNums();
            expectOutputSum += item.getExpectOutput();
            expectPurchaseSum += item.getExpectPurchase();
            expectReceivingSum += item.getExpectReceiving();
            expectPickingSum += item.getExpectPicking();
        }
        res.setExpectNumsSum(expectNumsSum);
        res.setOrderNumsSum(orderNumsSum);
        res.setStockNumsSum(stockNumsSum);
        res.setExpectOutputSum(expectOutputSum);
        res.setExpectPurchaseSum(expectPurchaseSum);
        res.setExpectReceivingSum(expectReceivingSum);
        res.setExpectPickingSum(expectPickingSum);
        return Result.success(res);
    }

//    @GetMapping("/purtaPh")
//    @ApiOperation("请购平衡总表")
//    public void purtaPh(){
//
//    }
}
